home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 1236 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.6 KB

  1. Path: news1.cris.com!voyager!Crawford
  2. From: Crawford@voyager.cris.com (CRAWFORD)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: returning a string from a function
  5. Date: 12 Jan 1996 09:41:50 -0500
  6. Organization: Concentric Internet Services
  7. Message-ID: <Crawford.821457029@voyager>
  8. References: <4d4uh8$q46@mailhost.mwmicro.com>
  9. Reply-To: crawford@iac.net
  10. NNTP-Posting-Host: voyager-fddi.cris.com
  11.  
  12. aschlies@citynet.net (Tony Schliesser) writes:
  13. >char function_name(char in_string[80])
  14. >{
  15. >    char value[80];
  16. >    ...value takes on part of the value of the last 10 characters
  17. >      of in_string.
  18. >    return(value);
  19. >}
  20. >jWhen this function is done, it only returns the first character.  I
  21. >"watched" the program execution and it shows that value indeed has the
  22. >last 10 characters.  Any clues as to why the calling routine only gets
  23. >the one character??
  24.  
  25.     There are _lots_ of problems with the function definition
  26. you've given us:
  27.  
  28.     1. You're declaring the function to return a character, and
  29. your argument for return is a character pointer.
  30.     2. You're attempting to return a pointer to an automatic
  31. variable.
  32.  
  33.     A more correct version is:
  34.  
  35. char *function_name (char in_string[])
  36. {
  37.     static char value[80];
  38.  
  39.     /* copy the characters */
  40.  
  41.     return value;
  42. }
  43.  
  44.     Since you want to return more than one character, the function
  45. has to return a pointer to a string. You have to declare value as
  46. static because otherwise it's allocated on the stack and will probably
  47. be corrupted -- or you'll modify its contents and corrupt the stack
  48. yourself.
  49.  
  50. -- 
  51. Creature of the wheel, master of the internal combustion engine.
  52.  
  53. Robert Crawford                crawford@iac.net
  54. http://www.iac.net/~crawford
  55.